import requests
import threading
import sys
import os
from concurrent.futures import ThreadPoolExecutor

sys.path.append(
    os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
)

from model.park_location_record import ParkRecord
from database.park_location_record_table import ParkRecordTable
import spider_config
from common.logger import logger
import common.http as http
lock = threading.RLock()

def get_headers():
    headers = {
        "Host": "owner.irainone.com",
        "Connection": "keep-alive",
        "Accept": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiZy9NRDRmUTdETmh5QmFMcW9xWlAzQT09Iiwib3Blbl9pZCI6IlV1cUxvVlN6VXNxUEluam9kREJIVXJrdWVXdTdpNlB6YTNuUzEyTVp5L0E9IiwidW5pb25faWQiOiJGQ3VjbXEwd3VBSmltVHY5anVRTEE4UzJsQlFBbHBkWEVjcURtT1dZMVNvPSIsInNlc3Npb25fa2V5IjoiejUrUXFxaTlLNXA5R0FUTm1qRDFsZnRDZFVsZE1JZXRRZ1N2c0paNFpuaz0iLCJleHAiOjE3MDA5OTYzMTcsImlzcyI6IlBhcmtpbmdXYW5nIiwibmJmIjoxNzAwOTg4MTE3fQ.fMYdl9dWRffOah_V3E2h79ET-6i-Ac80k4ZWp5SOSuA",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.34(0x1800222a) NetType/WIFI Language/en",
        "Content-Type": "application/json; charset=UTF-8",
        "Referer": "https://servicewechat.com/wx5c9141d32d5de2c6/159/page-frame.html",
    }
    return headers

def get_parking():
    url = 'https://owner.irainone.com/location/city?id='
    rspJson = http.get(url, headers=get_headers()).json()
    for item in rspJson["data"]:
        rspJson2 = http.get(f"https://owner.irainone.com/location/city?id={item['id']}", headers=get_headers()).json()
        for item2 in rspJson2["data"]:
            data = {
                "city_code":str(item2["id"]),
                "park_name":"",
                "lng":item2["lat"],
                "lat":item2["lng"],
                "page":1,
                "page_size":999999,
                "src":"weapp"
            }
            
            rspJson3 = http.post(url = "https://owner.irainone.com/mall/park_list", json=data, headers=get_headers()).json()
            with ParkRecordTable(spider_config.airun_park_id) as table:
                for item3 in rspJson3["data"]:
                    try:
                        record = ParkRecord()
                        record.park_code = item3["park_code"]
                        record.lat = item3["gps"]["lat"]
                        record.lon = item3["gps"]["lng"]
                        record.park_name = item3["park_name"]
                        record.address = item["name"] + item2["name"] + item3["addr"]
                        record.platform_id = spider_config.airun_park_id
                        if not table.exist("park_code", record.park_code):
                            table.insert(record)
                            logger.success(f"{record.park_name}({record.address})")
                    except Exception as e:
                        logger.exception(e)
                table.commit()
            
if __name__ == '__main__':
    get_parking()